#!/bin/sh
exec @GUILE@ -s $0 "$@"
!#

(if (< (length (command-line)) 2)
    (begin
      (display "Missing command line argument \"source directory\"")
      (exit 1)))

(define *srcdir* (list-ref (command-line) 1))
(define *currency-file* (string-append *srcdir* "/" "iso-4217-currencies.scm"))
(define *c-file-name* "iso-4217-currencies.c")

(define (generate-currency-c-code form output-port)
  ;; Check for correct number of arguments
  (if (and (list? form)
	   (eq? 9 (length form)))
      ;; Assign arguments
      (let ((fullname (list-ref form 0))
	    (unitname (list-ref form 1))
	    (partname (list-ref form 2))
	    (namespace (list-ref form 3))
	    (mnemonic (list-ref form 4))
	    (exchange-code (list-ref form 5))
	    (parts-per-unit (list-ref form 6))
	    (smallest-fraction (list-ref form 7))
	    (local-symbol (list-ref form 8)))
	;; Check for correct types of arguments
	(if (and (string? fullname)
		 (string? unitname)
		 (string? partname)
		 (string? namespace)
		 (string? mnemonic)
		 (string? exchange-code)
		 (number? parts-per-unit)
		 (number? smallest-fraction)
		 (string? local-symbol))

	    ;; And print the output line
	    (format
	     output-port "
  {
    const char *fullname = ~S;
    gnc_commodity *c = gnc_commodity_new(book,
					 CUR_I18N(fullname),
                                         ~S,
                                         ~S,
                                         ~S,
                                         ~S);\n
    if(!c) {
      PWARN(\"failed to create commodity for currency %s\", fullname);
    } else {
      if(!gnc_commodity_table_insert(table, c)) {
        PWARN(\"failed to insert %s into commodity table\", fullname);
      }
    }
  }\n"
	     fullname
	     namespace
	     mnemonic
	     exchange-code
	     smallest-fraction)

	    ;; Sorry, code doubling of the error message, but whatever.
	    (begin
	      (display "Bad currency data (wrong column data) at line: ")
	      (display form)
	      (newline)
	      #f)))

      (begin
        (display "Bad currency data (wrong number of columns) at line: ")
        (display form)
        (newline)
        #f)))

(define (generate-currencies-c-code)
  (call-with-input-file *currency-file*
    (lambda (input-port)
      (call-with-output-file *c-file-name*
        (lambda (output-port)
          (let loop ((form (read input-port)))
            (if (eof-object? form)
                #t
                (if (generate-currency-c-code form output-port)
                    (loop (read input-port))
                    #f))))))))

(if (not (generate-currencies-c-code))
    (begin
      (display "Unable to generate iso-4217 currency C code.\n")
      (exit 1))
    (exit 0))

;; Local Variables:
;; mode: scheme
;; End:
